package org.example.bifunction;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Java8BiFunction4 {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("node", "c++", "java", "javascript");
        List<String> result = filterList(list,3,Java8BiFunction4::filterByLength);
        System.err.println(JSONObject.toJSONString(result,true));
        List<String> result1 = filterList(list, 3, new BiFunction<String, Integer, String>() {
            @Override
            public String apply(String s, Integer integer) {
                if(s.length() > integer){
                    return s;
                }
                return null;
            }
        });
        System.err.println(JSONObject.toJSONString(result1,true));

        List<String> result2 = filterList(list, "c", (s,c) ->{
            if (s.contains(c)) {
                return s;
            }
            return null;
        });
        System.err.println(JSONObject.toJSONString(result2));

        List<Integer> numbers = IntStream.range(1,5).boxed().collect(Collectors.toList());
        List<Integer> result3 = filterList(numbers,2,(a,b) ->{
            if (a % b == 0) {
                return a;
            }else{
                return null;
            }
        });
        System.err.println(JSONObject.toJSONString(result3));
    }

    static String filterByLength(String str,Integer size){
        if (str.length() > size) {
            return str;
        }else{
            return null;
        }
    }

    /**
     *
     * @param list
     * @param condition
     * @param func
     * @param <T> 入参类型
     * @param <U> 条件
     * @param <R> 返回值类型
     * @return
     */
    static <T,U,R> List<R> filterList(List<T> list, U condition, BiFunction<T,U,R> func){
        List<R> results = new ArrayList<>();
        for (T t : list) {
            R apply = func.apply(t,condition);
            if (apply != null) {
                results.add(apply);
            }
        }
        return results;
    }
}
